/*
 * @param {*}  左侧输入框输入的值转化成的 js 数据
 * @return {*} 根据传入的数据生成对应的 js 格式数据
 */
let generateData = (data) => {
  // TODO：待补充代码
  const regex1 = /\{\{repeat\(\s*(\d+)\s*,\s*(\d+)\s*\)}}/;
  const regex2 = /\{\{repeat\(\s*(\d+)\s*\s*\s*\)}}/;
  const boolRegex = /\{\{bool\(\s*\)}}/;
  const numRegex = /\{\{integer\(\s*(\d+)\s*,\s*(\d+)\s*\)}}/;

  if (regex1.test(data[0])) {
    const matches = data[0].match(regex1);
    if (matches) {
      const n = parseInt(matches[1], 10);
      const m = parseInt(matches[2], 10);
      const ran = Math.floor(Math.random() * (m - n + 1)) + n;
      data.shift();
      const originalData = data.slice();
      let result = [];
      for (let i = 0; i < ran; i++) {
        const copied = originalData.map(item => ({
          ...item
        }));
        result = result.concat(copied);
      }
      data = result;
    }
  } else if (regex2.test(data[0])) {
    const matches = data[0].match(regex2);
    if (matches) {
      const n = parseInt(matches[1], 10);
      data.shift();
      const originalData = data.slice();
      let result = [];
      for (let i = 0; i < n; i++) {
        const copied = originalData.map(item => ({
          ...item
        }));
        result = result.concat(copied);
      }
      data = result;
    }
  }
  if (Array.isArray(data)) {
    console.log("这是数组结构");
    data.forEach(item => {
      for (let key in item) {
        if (boolRegex.test(item[key])) {
          item[key] = Math.random() > 0.5;
        } else if (numRegex.test(item[key])) {
          const matches = item[key].match(numRegex);
          if (matches) {
            const n = parseInt(matches[1], 10);
            const m = parseInt(matches[2], 10);
            item[key] = Math.floor(Math.random() * (m - n + 1)) + n;
          }
        }
      }
    })
  } else if (typeof data === 'object' && data !== null) {
    console.log("这是对象结构");
    for (let key in data) {
      if (boolRegex.test(data[key])) {
        data[key] = Math.random() > 0.5;
      } else if (numRegex.test(data[key])) {
        const matches = data[key].match(numRegex);
        if (matches) {
          const n = parseInt(matches[1], 10);
          const m = parseInt(matches[2], 10);
          data[key] = Math.floor(Math.random() * (m - n + 1)) + n;
        }
      }
    }
  }
  return data;
};

module.exports = {
  generateData
};